const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const { auth } = require('./middleware/auth');
const db = require('./config/db');
const errorHandler = require('./middleware/error');
const { apiLimiter, authLimiter } = require('./middleware/rateLimit');
const logger = require('./utils/logger');

// 导入路由
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/users');
const productRoutes = require('./routes/products');
const productCategoryRoutes = require('./routes/productCategories');
const productReviewRoutes = require('./routes/productReviews');
const productFavoriteRoutes = require('./routes/productFavorites');
const uploadRoutes = require('./routes/upload');
const backupRoutes = require('./routes/backup');

const app = express();

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 请求日志中间件 - 放在所有路由之前
app.use((req, res, next) => {
  const startTime = new Date();
  console.log(`[${startTime.toISOString()}] ${req.method} ${req.url}`);

  // 在响应结束时记录完整信息
  res.on('finish', () => {
    const duration = new Date() - startTime;
    const logMessage = `[${new Date().toISOString()}] ${req.method} ${req.url} - ${res.statusCode} - ${duration}ms`;
    console.log(logMessage);
  });

  next();
});

// 静态文件服务
app.use('/uploads', express.static('uploads'));

// 应用速率限制
app.use('/api/', apiLimiter);
app.use('/api/auth', authLimiter);

// 不需要认证的路由
app.use('/api/auth', authRoutes);
app.use('/api/products', productRoutes);
app.use('/api/categories', productCategoryRoutes);

// 需要认证的路由
app.use('/api/users', auth, userRoutes);
app.use('/api/reviews', auth, productReviewRoutes);
app.use('/api/favorites', auth, productFavoriteRoutes);
app.use('/api/upload', auth, uploadRoutes);
app.use('/api/backup', auth, backupRoutes);

// 请求日志中间件
app.use(logger.logRequest);

// 错误处理中间件
app.use(logger.logError);

// 错误处理中间件
app.use(errorHandler);

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 